import axios from "axios";
import store from "@/store";
import getpageName from "../../utils/gw/getPageName"

//任务队列
let tasks = [];
let dataStore;
let pageName= getpageName()
export const baseComponentNames = {
	GuessYouLike: {},//猜你喜欢组件
	HomeCarousel: {},//轮播
	NewZone: {},//横幅图片
	UserCard: {},//扫一扫会员卡
	HomeNotice: {},//公告
	ProductItemNew: {},//十格图片
	FeaturedGoodsNew: {},//五宫格图片
	FirstClassifyNew: {},//楼层导航
	activitiesTwoPro: {},//两列下滑
	activitiesNinePro: {},//三列下滑
	activitiesThreePic: {},//三列横滑
	activitiesOnePro: {},//单列下滑
	// activitiesbanner: {},
	activitiesSlidePic: {},//下滑图片模块（可以选择一行一列一行两列一行三列）
	ActivitieCoupons: {},//固定优惠券
	ActivitieCoupons2: {},//自定义优惠券
	TabHead: {},  //Tab导航组件
	// activitiesNewBot: {},
	// activitiesThreePic: {}
}
//清除内存中的dataStore
export function clearDataStoreForMemory() {
	dataStore = {};
}
const initMethods = (pageName) => {
	let _methods = {
		"home": () => {},
		"NewThematicActivities": () => {}
	}
	return _methods[pageName] || _methods
	
}
function initDataStore() {
	// console.log("localforage", localforage);
	dataStore = sessionStorage.getItem('dataStore');
	console.log("dataStore", dataStore);
	let exits = false;//缓存的数据是否存在
	if (!dataStore) {
		dataStore = {
			...baseComponentNames
		}
	} else {
		exits = true;
	}
	return Promise.resolve({
		exits,
		dataStore: exits ? JSON.parse(dataStore) : dataStore
	});
};

async function initData() {
	let result = await initDataStore();
	console.log("initDataStore---result", result);
	if (result.exits) {
		console.log("存在缓存，直接返回缓存数据")
		return result.dataStore;
	}
	let pageTreeContent = store.getters['gw/getRealComponentsList'][0][1] || [];
	//第一步拿到所有的id
	let requestData = [];
	for (var i = 0; i < pageTreeContent.length; i++) {
		requestData.push({
			id: pageTreeContent[i].id,
			componentName: pageTreeContent[i].componentName,
		});
	}
	requestData.forEach(item => {
		startQueryData(item);
	});
	// console.log("任务队列", tasks);
	await Promise.all(tasks);
	console.log("数据请求完成并且构建完dataStore", dataStore);
	sessionStorage.setItem("dataStore", JSON.stringify(dataStore));
	return dataStore;
}
//开始根据type和id值去请求对应的数据
function startQueryData(requestParams) {
	switch (requestParams.componentName) {
		case 'HomeCarousel':
			tasks.push(queryBanner(requestParams.id, requestParams.componentName));
			break;
		case 'ProductItemNew':
			tasks.push(queryProductItemNew(requestParams.id, requestParams.componentName));
			break;
		case 'FeaturedGoodsNew':
			tasks.push(queryFeaturedGoodsNew(requestParams.id, requestParams.componentName));
			break;
		case 'FirstClassifyNew':
			tasks.push(queryfinalListNew(requestParams.id, requestParams.componentName));
			break;
		case 'NewZone':
			tasks.push(queryNewZone(requestParams.id, requestParams.componentName));
			break;
		default:
			break;
	}
}
//轮播图片数据
function queryBanner(id, componentName) {
	let url = window.api.goods_host + window.api.home_ad;
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}
//菜单图标（新分类数据）
function queryProductItemNew(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/icon';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}
//促销活动专区(新的特色商品)
function queryFeaturedGoodsNew(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/pro_act';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	});
}
//新人专区
function queryNewZone(id, componentName) {
	let url = window.api.goods_host + '/resourceConfig/mobile/newborn';
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	})
}
//新分类推荐数据
function queryfinalListNew(id, componentName) {
	let url = window.api.goods_host + "/resourceConfig/mobile/new_qc";
	let options = {
		method: "get",
		url,
		params: {
			enterpriseCode: api.enterpriseCode,
			storeCode: localStorage.getItem('storeCode'),
			usePlatform: "wap",
			relGroup: id
		},
	}
	return axios(options).then(data => {
		if (data.data.data) {
			getDataStoreChange(id, componentName, data.data.data)
		}
	})
}
//动态改变模板数据
async function getDataStoreChange(id, componentName, data) {
	// console.log("data刘小娜", data);
	try {
		dataStore[componentName] = {
			...dataStore[componentName],
			[id]: data[0] ? data[0][id] : []
		}
	} catch (err) {
		console.log("填充数据报错", err);
	}
}

export default initData